from qiniu import Auth
from rest_framework.views import APIView
from rest_framework.response import Response


class QiniuTokenGenerator:
    def __init__(self, access_key, secret_key, bucket_name):
        """
        初始化七牛云鉴权对象
        :param access_key: 七牛云的 Access Key
        :param secret_key: 七牛云的 Secret Key
        :param bucket_name: 要上传的空间名称
        """
        self.access_key = access_key
        self.secret_key = secret_key
        self.bucket_name = bucket_name
        self.auth = Auth(access_key, secret_key)

    def generate_upload_token(self, expires=3600):
        """
        生成七牛云上传 token
        :param expires: token 过期时间，单位为秒，默认为 3600 秒（1 小时）
        :return: 生成的上传 token
        """
        return self.auth.upload_token(self.bucket_name, expires=expires)


def qiniu_token():
    """
    生成七牛云上传 token 的函数
    :return: 生成的上传 token
    """
    access_key = 'i4AZwb8GrukBN4x82amxQwPOwMPHt-7Fphle9fwI'
    secret_key = 'PREeYGiY2QU5rT3gw1DC1FJ38omMU0ZKAmI7lzLR'
    bucket_name = 'h2410b'
    generator = QiniuTokenGenerator(access_key, secret_key, bucket_name)
    return generator.generate_upload_token()


class QnToken(APIView):
    def get(self, request):
        """
        通过 API 视图生成七牛云上传 token
        :param request: 请求对象
        :return: 包含上传 token 的响应
        """
        access_key = 'i4AZwb8GrukBN4x82amxQwPOwMPHt-7Fphle9fwI'
        secret_key = 'PREeYGiY2QU5rT3gw1DC1FJ38omMU0ZKAmI7lzLR'
        bucket_name = 'h2402a'
        generator = QiniuTokenGenerator(access_key, secret_key, bucket_name)
        token = generator.generate_upload_token()
        return Response({"code": 10000, 'data': token})

